package org.youchan.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Properties;

public class XMLResourceBundle {
	public static Properties getResource(String baseName) throws InvalidPropertiesFormatException, IOException {
		try {
			return getResource(baseName, Locale.getDefault());
		} catch (MissingResourceException e) {
		}
		return getResource(baseName, null);
	}
	
	public static Properties getResource(String baseName, Locale locale) throws InvalidPropertiesFormatException, IOException {
		String basePath = "/" + baseName.replaceAll("\\.", "/");

		String localeSuffix = "";
		if (locale != null) {
			localeSuffix = "_" + locale.getLanguage();
		}
		String resourceName = basePath + localeSuffix + ".properties";
		
		InputStream is = XMLResourceBundle.class.getResourceAsStream(resourceName);
		if (is == null) {
			String className = baseName.replaceAll("(.*)\\.\\w+$", "$1");
			String name = baseName.replaceAll(".*\\.(\\w+)$", "$1");
			throw new MissingResourceException("can't load resource: " + resourceName, className, name);
		}
		Properties prop = new Properties();
		prop.loadFromXML(is);
		return prop;
	}
}
